import React, { useEffect, useState } from "react";
import { Button, Space, Switch, Table, Row, Col, Modal } from "antd";
import type { ColumnsType } from "antd/es/table";
import { categoryGet, ICateParams } from "@/api/course";
import CatePublic from "./CatePublic";
import { useAppSelector } from "@/store/hook";

// const data: ICateParams[] = [
//   {
//     objectId: "1",
//     cateName: "John Brown",
//     fatherId: "0-0",
//     status: true,
//   },
// ];

const CateList: React.FC = () => {
  const [data, setData] = useState<ICateParams[]>([]);
  const [isModalOpen, setIsModalOpen] = useState<boolean>(false);
  const { user } = useAppSelector((state) => state);
  const columns: ColumnsType<ICateParams> = [
    {
      title: "分类ID",
      dataIndex: "objectId",
      key: "objectId",
    },
    {
      title: "分类名称",
      dataIndex: "cateName",
      key: "cateName",
    },
    {
      title: "父级ID",
      dataIndex: "fatherId",
      key: "fatherId",
    },
    {
      title: "是否上架",
      key: "status",
      dataIndex: "status",
      render: (bool) => {
        return <Switch checked={bool} />;
      },
    },
    {
      title: "操作",
      key: "action",
      render: (_, record) => (
        <Space size="middle">
          <Button type="primary">编辑</Button>
          {user.userInfo!.roleName === "超级管理员" ? (
            <Button type="primary" danger>
              删除
            </Button>
          ) : (
            ""
          )}
        </Space>
      ),
    },
  ];
  useEffect(() => {
    categoryGet({}).then((res) => {
      console.log(res);
      let { results } = res.data;
      let arr = results.filter((item: ICateParams) => item.fatherId == "0-0");
      arr.forEach((item: ICateParams) => {
        item.children = results.filter(
          (itm: ICateParams) => item.objectId == itm.fatherId
        );
      });
      console.log(arr);
      setData(arr);
    });
  }, []);
  const handleDataClose = (cateObj: ICateParams) => {
    setIsModalOpen(false);
    if (cateObj.fatherId == "0-0") {
      data.push(cateObj);
    } else {
      let children = data.find((item) => item.objectId == cateObj.fatherId)
        ?.children as ICateParams[];
      children.push(cateObj);
    }
    setData([...data]);
  };
  return (
    <div>
      <Row justify="end">
        <Col>
          <Button
            type="primary"
            onClick={() => {
              setIsModalOpen(true);
            }}
          >
            新增分类
          </Button>
        </Col>
      </Row>
      <Table columns={columns} dataSource={data} rowKey="objectId" />;
      <Modal
        title="新增分类"
        open={isModalOpen}
        footer={null}
        onCancel={() => {
          setIsModalOpen(false);
        }}
      >
        <CatePublic
          setIsModalOpen={setIsModalOpen}
          handleDataClose={handleDataClose}
        />
      </Modal>
    </div>
  );
};

export default CateList;
